<?php

use Drupal\shusy_category\Entity\ShusyCategory;
use Drupal\shusy_category_store_rebate\Entity\ShusyCategoryStoreRebate;
use Drupal\shusy_category_vip_rebate\Entity\ShusyCategoryVipRebate;
use Drupal\shusy_store_level\Entity\ShusyStoreLevel;
use Drupal\shusy_vip\Entity\ShusyVip;

function shusy_category_shusy_category_entity_form($form, &$form_state, ShusyCategory $e, $op) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_category') . '/shusy_category.forms.inc';
  $form_state[ShusyCategory::class] = $e;

  $form['name'] = [
    '#type' => 'textfield',
    '#title' => t('分类名'),
    '#required' => TRUE,
    '#default_value' => $e->name,
  ];
  $form['period'] = [
    '#type' => 'textfield',
    '#title' => t('账期 仅一级分类有效'),
    '#required' => TRUE,
    '#default_value' => $e->period,
    '#element_validate' => ['element_validate_integer'],
    '#description' => t('账期 单位天'),
    '#size' => 8,
    //'#disabled' => TRUE,
  ];
  $form['icon'] = [
    '#title' => t('分类图标'),
    '#type' => 'managed_file',
    '#default_value' => $e->icon,
    '#upload_location' => 'public://tmp/',
    '#description' => t('分类3级 需上传图标 否则使用默认图标'),
  ];
  $form['status'] = [
    '#type' => 'select',
    '#title' => t('状态'),
    '#options' => $e->getStatusOptions(),
    '#default_value' => $e->status,
    '#chosen' => TRUE,
    '#required' => TRUE,
  ];

  $form["items"] = [
    '#type' => 'fieldset',
    '#title' => t('店铺进货折扣'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE,
    '#prefix' => '<div id="items-form-wrapper">',
    '#suffix' => '</div>',
    '#theme' => 'shusy_category_form_items',
  ];
  $levels = shusy_store_level_load_multiple(FALSE, [], TRUE);
  $form_state['items'] = $levels;
  foreach ($levels as $level) {
    if ($level instanceof ShusyStoreLevel) {
      $rebate = 10000;
      $status = 0;
      $sets = shusy_category_store_rebate_load_multiple(FALSE, [
        'category_id' => $e->id,
        'level_id' => $level->id,
      ]);
      if (!empty($sets)) {
        $set = reset($sets);
        if ($set instanceof ShusyCategoryStoreRebate) {
          $rebate = $set->rebate;
          $status = $set->status;
        }
      }
      $form['items'][] = [
        'id' => [
          '#type' => 'value',
          '#value' => $level->id,
        ],
        'name' => [
          '#title' => t('店铺级别'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => $level->name,
          '#disabled' => TRUE,
        ],
        'rebate' => [
          '#type' => 'textfield',
          '#title_display' => 'invisible',
          '#title' => t('比例折扣'),
          '#required' => TRUE,
          '#default_value' => $rebate / 100,
          '#description' => t('保留2位小数'),
          '#field_suffix' => t('%'),
          '#maxlength' => 8,
          '#size' => 8,
        ],
        'status' => [
          '#title' => t('启用'),
          '#title_display' => 'invisible',
          '#type' => 'checkbox',
          '#default_value' => $status,
        ],
      ];
    }
  }

  $form["vips"] = [
    '#type' => 'fieldset',
    '#title' => t('VIP折扣'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
    '#tree' => TRUE,
    '#prefix' => '<div id="vips-form-wrapper">',
    '#suffix' => '</div>',
    '#theme' => 'shusy_category_form_vips',
  ];
  $vips = shusy_vip_load_multiple(FALSE, [], TRUE);
  $form_state['vips'] = $vips;
  foreach ($vips as $vip) {
    if ($vip instanceof ShusyVip) {
      $rebate = 10000;
      $status = 0;
      $sets = shusy_category_vip_rebate_load_multiple(FALSE, [
        'category_id' => $e->id,
        'vip_id' => $vip->id,
      ]);
      if (!empty($sets)) {
        $set = reset($sets);
        if ($set instanceof ShusyCategoryVipRebate) {
          $rebate = $set->rebate;
          $status = $set->status;
        }
      }
      $form['vips'][] = [
        'id' => [
          '#type' => 'value',
          '#value' => $vip->id,
        ],
        'name' => [
          '#title' => t('VIP'),
          '#title_display' => 'invisible',
          '#type' => 'textfield',
          '#required' => TRUE,
          '#default_value' => $vip->name,
          '#disabled' => TRUE,
        ],
        'rebate' => [
          '#type' => 'textfield',
          '#title_display' => 'invisible',
          '#title' => t('比例折扣'),
          '#required' => TRUE,
          '#default_value' => $rebate / 100,
          '#description' => t('保留2位小数'),
          '#field_suffix' => t('%'),
          '#maxlength' => 8,
          '#size' => 8,
        ],
        'status' => [
          '#title' => t('启用'),
          '#title_display' => 'invisible',
          '#type' => 'checkbox',
          '#default_value' => $status,
        ],
      ];
    }
  }


  field_attach_form($e->entityType(), $e, $form, $form_state);

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('保存'),
  ];
  return $form;
}

function theme_shusy_category_form_items($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = [];
  foreach (element_children($form) as $id) {
    $form[$id]['weight']['#attributes']['class'] = ['item-weight'];
    $rows[] = [
      'data' => [
        drupal_render($form[$id]['name']),
        drupal_render($form[$id]['rebate']),
        drupal_render($form[$id]['status']),
      ],
      'class' => ['draggable'],
    ];
  }
  $header = [
    t('店铺级别'),
    t('比例折扣 0(免费) - 100(不打折)'),
    t('启用'),
  ];

  $table_id = 'items-table';
  $form['items_markup']['markup']['#markup'] = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  return $output;
}

function theme_shusy_category_form_vips($variables) {
  $output = '';
  $form = $variables['form'];
  $rows = [];
  foreach (element_children($form) as $id) {
    $form[$id]['weight']['#attributes']['class'] = ['item-weight'];
    $rows[] = [
      'data' => [
        drupal_render($form[$id]['name']),
        drupal_render($form[$id]['rebate']),
        drupal_render($form[$id]['status']),
      ],
      'class' => ['draggable'],
    ];
  }
  $header = [
    t('VIP'),
    t('比例折扣 0(免费) - 100(不打折)'),
    t('启用'),
  ];

  $table_id = 'items-table';
  $form['items_markup']['markup']['#markup'] = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  return $output;
}

function shusy_category_shusy_category_entity_form_submit($form, &$form_state) {
  $e = $form_state[ShusyCategory::class];
  if ($e instanceof ShusyCategory) {
    entity_form_submit_build_entity($e->entityType(), $e, $form, $form_state);
    $e->save();

    if (!empty($e->icon)) {
      $dir = "public://shusy_category/icon/" . format_date(REQUEST_TIME, 'custom', 'Y/m/d/') . drupal_random_key();
      $result = file_prepare_directory($dir);
      if (empty($result)) {
        drupal_mkdir($dir, 0777, TRUE);
      }
      $file = file_load($e->icon);
      if (!empty($file)) {
        $file->status = 1;
        file_save($file);
        $fid = $e->icon;
        $ext = pathinfo($file->uri, PATHINFO_EXTENSION);
        $file = file_move($file, "{$dir}/{$e->id}_{$fid}.{$ext}");
        file_usage_add($file, 'shusy_category', 'icon', $file->fid);
      }
    }

    $items = $form_state['values']['items'];
    foreach ($items as $item) {
      if (is_array($item)) {
        $level_id = $item['id'];
        $category_id = $e->id;
        $sets = shusy_category_store_rebate_load_multiple(FALSE, [
          'category_id' => $category_id,
          'level_id' => $level_id,
        ]);
        if (!empty($sets)) {
          $set = reset($sets);
        }
        else {
          $set = new ShusyCategoryStoreRebate;
          $set->category_id = $category_id;
          $set->level_id = $level_id;
        }
        if ($set instanceof ShusyCategoryStoreRebate) {
          $set->rebate = $item['rebate'] * 100;
          $set->status = $item['status'];
          $set->save();
        }
      }
    }

    $vips = $form_state['values']['vips'];
    foreach ($vips as $vip) {
      if (is_array($vip)) {
        $vip_id = $vip['id'];
        $category_id = $e->id;
        $sets = shusy_category_vip_rebate_load_multiple(FALSE, [
          'category_id' => $category_id,
          'vip_id' => $vip_id,
        ]);
        if (!empty($sets)) {
          $set = reset($sets);
        }
        else {
          $set = new ShusyCategoryVipRebate();
          $set->category_id = $category_id;
          $set->vip_id = $vip_id;
        }
        if ($set instanceof ShusyCategoryVipRebate) {
          $set->rebate = $vip['rebate'] * 100;
          $set->status = $vip['status'];
          $set->save();
        }
      }
    }

  }
}

function shusy_category_shusy_category_delete_form($form, &$form_state, ShusyCategory $e) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_category') . '/shusy_category.forms.inc';
  $form_state[ShusyCategory::class] = $e;
  return confirm_form($form,
    t('Are you sure you want to delete %title?', ['%title' => $e->label()]),
    'admin/content/shusy_category/' . $e->id,
    t('This action cannot be undone.'),
    t('Delete'),
    t('Cancel')
  );
}

function shusy_category_shusy_category_delete_form_submit($form, &$form_state) {
  $e = $form_state[ShusyCategory::class];
  if ($e instanceof ShusyCategory) {
    $e->delete();
  }
  $form_state['redirect'] = 'admin/structure/shusy_category';
}

function shusy_category_get_tree_data() {
  $rootnodes = db_query('SELECT id, name, icon, weight, parent,status,period
                       FROM {shusy_category}
                       WHERE (parent = 0)
                       ORDER BY weight ASC');
  $itemtree = [];
  $depth = -1;
  foreach ($rootnodes as $parent) {
    shusy_category_get_tree($parent, $itemtree, $depth);
  }
  return $itemtree;
}

function shusy_category_get_tree($parentitem, &$itemtree = [], &$depth = 0) {
  $depth++;
  $parentitem->depth = $depth;
  $itemtree[$parentitem->id] = $parentitem;
  $children = db_query('SELECT id, name, weight, icon, parent,status,period
                      FROM {shusy_category}
                      WHERE (parent = :parent)
                      ORDER BY weight ASC', [':parent' => $parentitem->id]);
  foreach ($children as $child) {
    if (!in_array($child->id, array_keys($itemtree))) {
      shusy_category_get_tree($child, $itemtree, $depth);
    }
  }
  $depth--;
}

function shusy_category_icon($icon) {
  if ($icon > 0) {
    $file = file_load($icon);
    if (!empty($file)) {
      return format_string("<img src='@src'>", ['@src' => image_style_url('icon', $file->uri)]);
    }
  }
  return '无';
}

function shusy_category_tree_form($form, &$form_state) {
  $form_state['build_info']['files']['form'] = drupal_get_path('module', 'shusy_category') . '/shusy_category.forms.inc';
  $form['categories']['#tree'] = TRUE;
  $es = shusy_category_get_tree_data();
  foreach ($es as $e) {
    $form['categories'][$e->id] = [
      'name' => [
        '#markup' => $e->name,
      ],
      'number' => [
        '#markup' => shusy_category_product_number($e->id),
      ],
      'icon' => [
        '#markup' => shusy_category_icon($e->icon),
      ],
      'period' => [
        '#markup' => $e->period,
      ],
      'id' => [
        '#type' => 'hidden',
        '#default_value' => $e->id,
      ],
      'parent' => [
        '#type' => 'hidden',
        '#default_value' => $e->parent,
      ],
      'weight' => [
        '#type' => 'weight',
        '#title' => t('Weight'),
        '#default_value' => $e->weight,
        '#delta' => 10,
        '#title_display' => 'invisible',
      ],
      'status' => [
        '#title' => t('启用'),
        '#title_display' => 'invisible',
        '#type' => 'checkbox',
        '#default_value' => $e->status,
      ],
      'depth' => [
        '#type' => 'hidden',
        '#value' => $e->depth,
      ],
      'edit' => [
        '#type' => 'link',
        '#title' => t('edit'),
        '#href' => "admin/content/shusy_category/{$e->id}/edit",
      ],
    ];
  }

  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('Save Changes'),
  ];
  return $form;
}

function theme_shusy_category_tree_form($variables) {
  $form = $variables['form'];
  $rows = [];
  foreach (element_children($form['categories']) as $id) {
    $form['categories'][$id]['weight']['#attributes']['class'] = ['item-weight'];
    $form['categories'][$id]['id']['#attributes']['class'] = ['item-id'];
    $form['categories'][$id]['parent']['#attributes']['class'] = ['item-parent'];
    $class = ['draggable'];

    $indent = theme('indentation', ['size' => $form['categories'][$id]['depth']['#value']]);
    unset($form['categories'][$id]['depth']);
    $weight = drupal_render($form['categories'][$id]['weight']);
    $weight .= drupal_render($form['categories'][$id]['id']);
    $weight .= drupal_render($form['categories'][$id]['parent']);
    $rows[] = [
      'data' => [
        $indent . drupal_render($form['categories'][$id]['name']),
        drupal_render($form['categories'][$id]['period']),
        drupal_render($form['categories'][$id]['number']),
        drupal_render($form['categories'][$id]['icon']),
        $weight,
        drupal_render($form['categories'][$id]['status']),
        drupal_render($form['categories'][$id]['edit']),
      ],
      'class' => $class,
    ];


  }
  $header = [
    t('分类名'),
    t('账期'),
    t('产品数量'),
    t('图标'),
    t('Weight'),
    t('Enable'),
    t('Edit'),
  ];
  $table_id = 'categories-table';
  $output = theme('table', [
    'header' => $header,
    'rows' => $rows,
    'attributes' => ['id' => $table_id],
  ]);
  $output .= drupal_render_children($form);
  drupal_add_tabledrag($table_id, 'match', 'parent', 'item-parent', 'item-parent', 'item-id', FALSE, 2);
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight', NULL, NULL, FALSE);
  return $output;
}

function shusy_category_tree_form_submit($form, &$form_state) {
  $categories = $form_state['values']['categories'];
  foreach ($categories as $category) {
    $item = shusy_category_load($category['id']);
    if ($item instanceof ShusyCategory) {
      $item->parent = $category['parent'];
      $item->weight = $category['weight'];
      $item->status = $category['status'];
      $item->depth = $category['depth'];
      $item->save();
    }
  }
}

function shusy_category_product_number(int $id) {
  $query = db_select('shusy_product_category', 'cp');
  $query->innerJoin('shusy_product', 'p', 'cp.product_id=p.id');
  $query->fields('cp', ['id']);
  $query->condition('cp.category_id', $id);
  $query->condition('cp.status', 1);
  return $query->execute()->rowCount();
}
